<?php
/************************
 *  Codenova.pl Project
 *  Created by: Kamil Mrzygłód
 *
 *  (c) 2013 by Codenova.pl
 *  All Right Reserved
 ***********************/

namespace Modules\JasminumNewsletter\Controllers;

use Gotcha\App\Extensions\GotchaCulturesExtension;
use Gotcha\App\Extensions\GotchaErrorsExtension;
use Gotcha\App\Extensions\GotchaLogsExtension;
use Gotcha\App\Extensions\HttpExtension;
use Gotcha\App\Framework\Controller;
use Gotcha\App\Types\String;
use GotchaDatabase\JasminumNewsletterMailsQuery;
use GotchaDatabase\JasminumNewsletters;
use GotchaDatabase\JasminumNewslettersQuery;

class AdminController extends Controller {
    public function Index() {
        return parent::View();
    }

    public function Create() {
        return parent::View();
    }

    public function CreatePost() {
        $http = new HttpExtension();

        if(empty($_POST['Title']) || empty($_POST['Body'])) {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Newsletter/Create?error=1'));
            exit;
        }

        // Add new content
        try {
            $static = new JasminumNewsletters();
            $static->setTitle($_POST['Title']);
            $static->setBody($_POST['Body']);

            // Set date
            $date = new \DateTime();

            $static->setCreationDate($date->format('Y-m-d'));
            $static->setCreationTime($date->format('H:i:s'));
            $static->save();
        } catch (\Exception $e) {
            GotchaLogsExtension::createNewLogEntry(new String($e->getMessage()));
            GotchaErrorsExtension::throwError(new String(GotchaCulturesExtension::getTranslation(new String('ERROR_DURING_EXECUTING_QUERY'))));
            exit;
        }

        header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Newsletter?create=1'));
        exit;
    }

    public function Edit() {
        return parent::View();
    }

    public function EditPost() {
        $http = new HttpExtension();

        // Validate input
        if(empty($_POST['Id']) || !isset($_POST['Id'])) {
            die('Error');
        }

        if(empty($_POST['Title']) || empty($_POST['Body']) || !isset($_POST['Title']) || !isset($_POST['Body'])) {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Newsletter/Edit?id='.$_POST['Id'].'&error=1'));
            exit;
        }

        // Update
        try {
            $static = JasminumNewslettersQuery::create()
                        ->findOneById($_POST['Id'])
                            ->setTitle($_POST['Title'])
                                ->setBody($_POST['Body'])
                                    ->save();
        } catch (\Exception $e) {
            GotchaLogsExtension::createNewLogEntry(new String($e->getMessage()));
            GotchaErrorsExtension::throwError(new String(GotchaCulturesExtension::getTranslation(new String('ERROR_DURING_EXECUTING_QUERY'))));
            exit;
        }

        header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Newsletter?edit=1'));
        exit;
    }

    public function EditMail() {
        return parent::View();
    }

    public function EditMailPost() {
        $http = new HttpExtension();

        // Validate input
        if(empty($_POST['Id'])) {
            die('Error');
        }

        if(empty($_POST['Mail'])) {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Newsletter/EditMail?id='.$_POST['Id'].'&error=1'));
            exit;
        }

        if(!filter_var($_POST['Mail'], FILTER_VALIDATE_EMAIL)) {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Newsletter/EditMail?id='.$_POST['Id'].'&error=2'));
            exit;
        }

        // Update
        try {
            $email = JasminumNewsletterMailsQuery::create()
                        ->findOneById($_POST['Id'])
                            ->setMail($_POST['Mail'])
                                ->save();
        } catch (\Exception $e) {
            GotchaLogsExtension::createNewLogEntry(new String($e->getMessage()));
            GotchaErrorsExtension::throwError(new String(GotchaCulturesExtension::getTranslation(new String('ERROR_DURING_EXECUTING_QUERY'))));
            exit;
        }

        header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Newsletter?edit=2'));
        exit;
    }

    public function Delete() {
        $http = new HttpExtension();

        // Validate input
        if(empty($_GET['id']) || !isset($_GET['id'])) {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Newsletter?error=2'));
            exit;
        }

        // Delete element
        try {
            JasminumNewslettersQuery::create()->findOneById($_GET['id'])->delete();
        } catch (\Exception $e) {
            GotchaLogsExtension::createNewLogEntry(new String($e->getMessage()));
            GotchaErrorsExtension::throwError(new String(GotchaCulturesExtension::getTranslation(new String('ERROR_DURING_EXECUTING_QUERY'))));
            exit;
        }

        header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Newsletter?delete=1'));
        exit;
    }

    public function DeleteMail() {
        $http = new HttpExtension();

        // Validate input
        if(empty($_GET['id']) || !isset($_GET['id'])) {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Newsletter?error=5'));
            exit;
        }

        // Delete element
        try {
            JasminumNewsletterMailsQuery::create()->findOneById($_GET['id'])->delete();
        } catch (\Exception $e) {
            GotchaLogsExtension::createNewLogEntry(new String($e->getMessage()));
            GotchaErrorsExtension::throwError(new String(GotchaCulturesExtension::getTranslation(new String('ERROR_DURING_EXECUTING_QUERY'))));
            exit;
        }

        header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Newsletter?delete=2'));
        exit;
    }

    public function Send() {
        $http = new HttpExtension();

        // Validate input
        if(empty($_GET['id']) || !isset($_GET['id'])) {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Newsletter?error=2'));
            exit;
        }

        try {
            // Newsletter about to be sent
            $newsletter = JasminumNewslettersQuery::create()
                            ->findOneById($_GET['id']);

            // Emails
            $emails = JasminumNewsletterMailsQuery::create()
                        ->find();
        } catch (\Exception $e) {
            GotchaLogsExtension::createNewLogEntry(new String($e->getMessage()));
            GotchaErrorsExtension::throwError(new String(GotchaCulturesExtension::getTranslation(new String('ERROR_DURING_EXECUTING_QUERY'))));
            exit;
        }

        // Prepare data to be sent
        $newsletterTitle = $newsletter->getTitle();
        $newsletterBody = $newsletter->getBody();

        // Prepare e-mail setup
        $mail = new \PHPMailer();

        $mail->IsSMTP(); // Use SMTP
        $mail->SMTPDebug = 0;
        $mail->SMTPAuth = true; // Use SMTP authentication
        $mail->SMTPSecure = "tls";
        $mail->Host = 'mail.restauracja-jasminum.pl';
        $mail->Port = 587;
        // $mail->Username = 'automat@codenova.drl.pl';
        $mail->Username = 'automat@restauracja-jasminum.pl';
        // $mail->Password = 'automat1';
        $mail->Password = ';Z;;gF(lBl++';
        $mail->CharSet = 'UTF-8';

        $mail->SetFrom('automat@restauracja-jasminum.pl', 'Restauracja Jasminum - Automat');
        $mail->Subject = $newsletterTitle;
        $mail->MsgHTML('<body>'.$newsletterBody.'</body>');

        // Add recipients
        // We only allow emails that pass PHP filter
        foreach($emails as $email) {
            if(filter_var($email->getMail(), FILTER_VALIDATE_EMAIL)) {
                $mail->AddAddress($email->getMail());
                if (!$mail->Send()) {
                    GotchaLogsExtension::createNewLogEntry(new String($mail->ErrorInfo));
                    GotchaErrorsExtension::throwError(new String(GotchaCulturesExtension::getTranslation(new String('ERROR_DURING_SENDING_MAIL'))));
                    exit;
                }
                $mail->ClearAllRecipients();
            }
        }

        // Set current newsletter as sent
        // Set date
        $date = new \DateTime();

        $newsletter->setSendDate($date->format('Y-m-d'));
        $newsletter->setSendTime($date->format('H:i:s'));
        $newsletter->save();

        // Data is saved, return a view
        header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Newsletter?sent=1'));
        exit;
    }

    public function returnNewsletters() {
        $newsletters = JasminumNewslettersQuery::create()
                        ->orderById()
                            ->find();

        // HTML cache
        $html = '';
        foreach ($newsletters as $newsletter) {
            $html .= '<tr>';
            $html .= sprintf('<td>%s</td><td>%s</td><td>%s</td><td>[ <a class="send" href="%s?id=%s">Wyślij</a> | <a href="%s?id=%s">Edytuj</a> | <a href="%s?id=%s" class="delete">Usuń</a> ]</td>', $newsletter->getTitle(), $newsletter->getCreationDate().' '.$newsletter->getCreationTime(), (is_null($newsletter->getSendDate()) ? 'Niewysłany' : $newsletter->getSendDate().' '.$newsletter->getSendTime()), parent::UrlContent('/Admin/Jasminum/Newsletter/Send'), $newsletter->getId(), parent::UrlContent('/Admin/Jasminum/Newsletter/Edit'), $newsletter->getId(), parent::UrlContent('/Admin/Jasminum/Newsletter/Delete'), $newsletter->getId());
            $html .= '</tr>';
        }

        if($newsletters->count() == 0) {
            $html .= '<tr><td colspan="4">Nie ma dodanych newsletterów.</td></tr>';
        }

        return $html;
    }

    public function returnEmails() {
        $emails = JasminumNewsletterMailsQuery::create()
                    ->orderById()
                        ->find();

        // HTML cache
        $html = '';
        foreach ($emails as $email) {
            $html .= '<tr>';
            $html .= sprintf('<td>%s</td><td>[ <a href="%s?id=%s">Edytuj</a> | <a href="%s?id=%s" class="delete">Usuń</a> ]</td>', $email->getMail(), parent::UrlContent('/Admin/Jasminum/Newsletter/EditMail'), $email->getId(), parent::UrlContent('/Admin/Jasminum/Newsletter/DeleteMail'), $email->getId());
            $html .= '</tr>';
        }

        if($emails->count() == 0) {
            $html .= '<tr><td colspan="4">Nie ma dodanych e-maili.</td></tr>';
        }

        return $html;
    }

    public function returnEmail($id) {
        $email = JasminumNewsletterMailsQuery::create()
                    ->findOneById($id);
        return $email;
    }

    public function returnContent($id) {
        $content = JasminumNewslettersQuery::create()
                    ->findOneById($id);
        return $content;
    }
}